/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.terminal.service;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.constants.UrlConstants;
import cn.iot.card.open.context.LoginContextHolder;
import cn.iot.card.open.ec.dto.ResponseDto;
import cn.iot.card.open.modular.model.ResultDTO;
import cn.iot.card.open.modular.token.TokenService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.terminal.dao.SmsMtRecordMapper;
import cn.iot.card.open.terminal.dto.BlankSmsDTO;
import cn.iot.card.open.terminal.dto.DownSmsDTO;
import cn.iot.card.open.terminal.dto.SmsSendRecordDTO;
import cn.iot.card.open.terminal.dto.SuccessSvcDetailDTO;
import cn.iot.card.open.terminal.dto.TemplateSmsDTO;
import cn.iot.card.open.terminal.dto.UpAndDownSmsRecordsDTO;
import cn.iot.card.open.terminal.model.SmsMtRecord;
import cn.iot.card.open.util.ApiRequestUtil;
import cn.iot.card.open.util.CommonUtil;
import cn.iot.card.open.util.JsonUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 发送下行短信
 */
@Service
@Slf4j
public class SmsSendService extends ServiceImpl<SmsMtRecordMapper, SmsMtRecord> {

    /**
     * apiRequestUtil
     */
    @Autowired
    private ApiRequestUtil apiRequestUtil;
    /**
     * tokenService
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 短信的条数，当代表短信发送成功，则说明短信发送全部失败，当代表短信发送失败，则说明短信发送全部成功
     */
    private static final String SMSNUM = "0";

    /**
     * 短信类型：1 - 模板短信
     */
    private static final String SMS_TEMPLATE = "1";

    /**
     * 短信类型：0 - 空短信
     */
    private static final String SMS_BLANK = "0";

    /**
     * 短信推送状态,0:成功,1:失败,2:等待回执
     */
    private static final String SMS_PUSH_STATUS_WAIT = "2";

    /**
     * 查询上/下行短信记录
     *
     * @param msisdns
     * @param smsSendRecordDTO
     * @return 返回 layui page info
     * @throws Exception
     * @author zhanlele
     * @date 20200225 20:24:10
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    public Page<Map<String, Object>> selectSmsSendRecord(String[] msisdns, SmsSendRecordDTO smsSendRecordDTO) {
        Page page = LayuiPageFactory.defaultPage();
        String pushStatus = smsSendRecordDTO.getSendStatus();
        String smsType = smsSendRecordDTO.getSmsType();
        String startDate = smsSendRecordDTO.getStartDate();
        String endDate = smsSendRecordDTO.getEndDate();
        return this.baseMapper.getSmsMtRecordList(page, msisdns, pushStatus, smsType, startDate, endDate);
    }

    /**
     * 准备请求参数
     *
     * @param transId
     * @param upAndDownSmsRecordsDTO
     * @return 返回 map
     * @throws Exception
     * @author zhanlele
     * @date 20200225 17:30:42
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    private Map<String, String> prepareRequestParameter(String transId, UpAndDownSmsRecordsDTO upAndDownSmsRecordsDTO) {
        String msisdn = upAndDownSmsRecordsDTO.getMsisdn();
        String iccid = upAndDownSmsRecordsDTO.getIccid();
        String imsi = upAndDownSmsRecordsDTO.getImsi();
        String startDate = upAndDownSmsRecordsDTO.getStartDate();
        String endDate = upAndDownSmsRecordsDTO.getEndDate();

        String cardType = "";
        String cardNum = "";
        if (StringUtils.isNotBlank(msisdn)) {
            cardType = Constants.REQUEST_PARAM_MSISDN;
            cardNum = msisdn;
        } else if (StringUtils.isBlank(msisdn) && StringUtils.isNotBlank(iccid)) {
            cardType = Constants.REQUEST_PARAM_ICCID;
            cardNum = iccid;
        } else if (StringUtils.isBlank(msisdn) && StringUtils.isNotBlank(imsi)) {
            cardType = Constants.REQUEST_PARAM_IMSI;
            cardNum = imsi;
        }

        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        switch (cardType) {
            case Constants.REQUEST_PARAM_MSISDN:
                parameterMap.put(Constants.REQUEST_PARAM_MSISDNS, cardNum);
                break;
            case Constants.REQUEST_PARAM_ICCID:
                parameterMap.put(Constants.REQUEST_PARAM_ICCIDS, cardNum);
                break;
            case Constants.REQUEST_PARAM_IMSI:
                parameterMap.put(Constants.REQUEST_PARAM_IMSIS, cardNum);
                break;
        }
        parameterMap.put(Constants.START_DATE, startDate);
        parameterMap.put(Constants.END_DATE, endDate);

        return parameterMap;
    }

    /**
     * 批量查询物联卡终端控制下行模板短信记录
     *
     * @param tokenValid token是否有效，false否，true是
     * @param accountId  账户ID
     * @param parameterMap
     * @return 返回 string
     * @throws Exception
     * @author zhanlele
     * @date 20200225 17:44:54
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResultDTO doRequestDownTemplateSms(boolean tokenValid, String accountId, Map<String, String> parameterMap) throws Exception {
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }

        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, UrlConstants.BATCH_QUERY_DOWN_SMS);

        String transId = parameterMap.get(Constants.REQUEST_PARAM_TRANSID);
        log.info("[{}] query doRequestDownTemplateSms request url is {}.", transId, methodUrl);
        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));

        return tokenResultDTO;
    }

    /**
     * 批量查询物联卡终端控制上行短信记录
     *
     * @param tokenValid token是否有效，false否，true是
     * @param accountId  账户ID
     * @param parameterMap
     * @return 返回 string
     * @throws Exception
     * @author zhanlele
     * @date 20200225 17:44:54
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResultDTO doRequestUpSms(boolean tokenValid, String accountId, Map<String, String> parameterMap) throws Exception {
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }

        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, UrlConstants.BATCH_QUERY_UP_SMS);

        String transId = parameterMap.get(Constants.REQUEST_PARAM_TRANSID);
        log.info("[{}] query doRequestUpSms request url is {}.", transId, methodUrl);
        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));

        return tokenResultDTO;
    }

    /**
     * 发送下行模板短信
     *
     * @param transId   流水号
     * @param accountId 账户ID
     * @param templateSmsDTO  模板短信对象
     * @return 返回 response dto
     * @throws Exception
     * @author zhanlele
     * @date 20200226 13:35:29
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResponseData sendTemplateSms(String transId, String accountId, TemplateSmsDTO templateSmsDTO) throws Exception {
        ResultDTO resultDTO = doRequestSendTemplateSms(true, accountId, transId, templateSmsDTO);
        if (!resultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(resultDTO.getCode());
            ResponseData responseData = new ResponseData();
            responseData.setCode(Integer.valueOf(errorCode.getCode()));
            responseData.setMessage(errorCode.getMsg());
            return responseData;
        }

        String responseStr = resultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取状态码，状态码为12021，TOKEN超出规定使用时限或错误
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] is invalid and start to get a new token.", transId, accountId);
            resultDTO = doRequestSendTemplateSms(false, accountId, transId, templateSmsDTO);
            if (!resultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(resultDTO.getCode());
                ResponseData responseData = new ResponseData();
                responseData.setCode(Integer.valueOf(errorCode.getCode()));
                responseData.setMessage(errorCode.getMsg());
                return responseData;
            }
        }

        responseStr = resultDTO.getMsg();
        log.info("[{}] sendDownTemplateSms, result string is {}.", transId, responseStr);
        ResponseDto<DownSmsDTO> responseDto = JsonUtil.parseJson(responseStr, new TypeReference<ResponseDto<DownSmsDTO>>(){});
        code = responseDto.getStatus();
        if (ErrorCode.SUCCESS.getCode().equals(code)) {
            // 解析模板短信发送结果
            templateSmsResultHandle(transId, responseDto.getResult(), templateSmsDTO);
            return ResponseData.success(JsonUtil.toJson(responseDto.getResult()));
        } else {
            // 请求失败
            log.warn("[{}] sendDownTemplateSms error, error message is {}.", transId, responseDto.getMessage());
            ResponseData responseData = new ResponseData();
            responseData.setCode(Integer.valueOf(code));
            responseData.setMessage(responseDto.getMessage());
            return responseData;
        }
    }

    /**
     * 处理发送成功的下行模板短信 - 发送记录入库
     * @param downSmsDTOs
     */
    private void templateSmsResultHandle(String transId, List<DownSmsDTO> downSmsDTOs, TemplateSmsDTO templateSmsDTO) {
        for (DownSmsDTO downSmsDTO : downSmsDTOs) {
            // 有发送成功的短信
            if (!SMSNUM.equals(downSmsDTO.getSuccSvcNum())) {
                List<SuccessSvcDetailDTO> successSvcDetailDTOS = downSmsDTO.getSuccessSvcDetail();
                if (null == successSvcDetailDTOS) {
//                    log.warn("[{}] successSvcDetail is null.", transId);
//                    return;
                    log.warn("[{}] successSvcDetail is null,start to create it.", transId);
                    String[] msisdns = templateSmsDTO.getMsisdns().split("_");
                    for (String msisdn : msisdns) {
                        SuccessSvcDetailDTO svcDetailDTO = new SuccessSvcDetailDTO();
                        svcDetailDTO.setStatus(ErrorCode.SUCCESS.getCode());
                        svcDetailDTO.setMsgId(transId);
                        svcDetailDTO.setMsisdn(msisdn);
                        successSvcDetailDTOS.add(svcDetailDTO);
                    }
                }

                for (SuccessSvcDetailDTO successSvcDetailDTO : successSvcDetailDTOS) {
                    SmsMtRecord smsMtRecord = new SmsMtRecord();
                    try {
                        if (ErrorCode.SUCCESS.getCode().equals(successSvcDetailDTO.getStatus())) {
                            smsMtRecord.setMsgid(successSvcDetailDTO.getMsgId());
                            smsMtRecord.setMsisdn(successSvcDetailDTO.getMsisdn());
                            smsMtRecord.setActionId(templateSmsDTO.getActionid());
                            smsMtRecord.setParams(templateSmsDTO.getParams());
                            smsMtRecord.setEncode(templateSmsDTO.getEncode());
                            smsMtRecord.setSmsType(SMS_TEMPLATE);
                            smsMtRecord.setPushStatus(SMS_PUSH_STATUS_WAIT);
                            Date date = new Date();
                            smsMtRecord.setSendTime(date);
                            long userId = LoginContextHolder.getContext().getUserId();
                            smsMtRecord.setCreateTime(date);
                            smsMtRecord.setCreateBy(userId);
                            smsMtRecord.setModifyTime(date);
                            smsMtRecord.setModifyBy(userId);
                            smsMtRecord.setDeleted(0);
                            this.baseMapper.insert(smsMtRecord);
                            log.info("[{}] success store down TemplateSms {}.", transId, smsMtRecord);
                        }
                    } catch (Exception e) {
                        log.error("[{}] store down TemplateSms {} error.", transId, smsMtRecord, e);
                    }
                }
            }
        }
    }

    /**
     * 调用发送下行模板短信接口
     *
     * @param tokenValid token是否有效
     * @param transId    流水号
     * @param accountId  账户ID
     * @param templateSmsDTO  模板短信对象
     * @return 返回 string
     * @throws Exception
     * @author zhanlele
     * @date 20200226 14:41:29
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResultDTO doRequestSendTemplateSms(boolean tokenValid, String accountId, String transId, TemplateSmsDTO templateSmsDTO) throws Exception {
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }

        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        parameterMap.put(Constants.REQUEST_PARAM_MSISDNS, templateSmsDTO.getMsisdns());
        parameterMap.put(Constants.ACTION_ID, templateSmsDTO.getActionid());
        parameterMap.put(Constants.PARAMS, templateSmsDTO.getParams());
        String encode = templateSmsDTO.getEncode();
        if (Constants.ENCODE_VALUE.equals(encode)) {
            parameterMap.put(Constants.ENCODE, encode);
        }

        String validTime = templateSmsDTO.getValidTime();
        if (StringUtils.isNoneEmpty(validTime)) {
            parameterMap.put(Constants.REQUEST_PARAM_VALIDTIME, validTime);
        }

        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, UrlConstants.OPERATE_DOWN_TEMPLATE_SMS);
        log.info("[{}] sendDownTemplateSms request url is {}.", transId, methodUrl);

        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));
        return tokenResultDTO;
    }

    /**
     * 发送下行空短信
     *
     * @param transId   流水号
     * @param accountId 账户ID
     * @param blankSmsDTO  空短信对象
     * @return 返回 response dto
     * @throws Exception
     * @author zhanlele
     * @date 20200226 14:46:40
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResponseData sendBlankSms(String transId, String accountId, BlankSmsDTO blankSmsDTO) throws Exception {
        ResultDTO resultDTO = doRequestSendBlankSms(true, transId, accountId, blankSmsDTO);
        if (!resultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(resultDTO.getCode());
            ResponseData responseData = new ResponseData();
            responseData.setCode(Integer.valueOf(errorCode.getCode()));
            responseData.setMessage(errorCode.getMsg());
            return responseData;
        }

        String responseStr = resultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取状态码，状态码为12021，TOKEN超出规定使用时限或错误
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] is invalid and start to get a new token.", transId, accountId);
            resultDTO = doRequestSendBlankSms(false, transId, accountId, blankSmsDTO);
            if (!resultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(resultDTO.getCode());
                ResponseData responseData = new ResponseData();
                responseData.setCode(Integer.valueOf(errorCode.getCode()));
                responseData.setMessage(errorCode.getMsg());
                return responseData;
            }
        }
        responseStr = resultDTO.getMsg();
        log.info("[{}] query sendDownBlankSms, result string is {}.", transId, responseStr);

        ResponseDto<DownSmsDTO> responseDto = JsonUtil.parseJson(responseStr, new TypeReference<ResponseDto<DownSmsDTO>>(){});
        code = responseDto.getStatus();
        if (ErrorCode.SUCCESS.getCode().equals(code)) {
            // 解析空短信发送结果
            blankSmsResultHandle(transId, responseDto.getResult(), blankSmsDTO);
            return ResponseData.success(JsonUtil.toJson(responseDto.getResult()));
        } else {
            // 请求失败
            log.warn("[{}] sendDownBlankSms error, error message is {}.", transId, responseDto.getMessage());
            ResponseData responseData = new ResponseData();
            responseData.setCode(Integer.valueOf(code));
            responseData.setMessage(responseDto.getMessage());
            return responseData;
        }
    }

    /**
     * 处理发送成功的下行空短信 - 发送记录入库
     * @param downSmsDTOs
     */
    private void blankSmsResultHandle(String transId, List<DownSmsDTO> downSmsDTOs, BlankSmsDTO blankSmsDTO) {
        for (DownSmsDTO downSmsDTO : downSmsDTOs) {
            // 有发送成功的短信
            if (!SMSNUM.equals(downSmsDTO.getSuccSvcNum())) {
                List<SuccessSvcDetailDTO> successSvcDetailDTOS = downSmsDTO.getSuccessSvcDetail();
                if (null == successSvcDetailDTOS) {
                    // 由于接口变更，有可能没有此对象，因此可以伪造
                    // log.warn("[{}] successSvcDetail is null.", transId);
                    // return;
                    log.warn("[{}] successSvcDetail is null,start to create it.", transId);
                    String[] msisdns = blankSmsDTO.getMsisdns().split("_");
                    for (String msisdn : msisdns) {
                        SuccessSvcDetailDTO svcDetailDTO = new SuccessSvcDetailDTO();
                        svcDetailDTO.setStatus(ErrorCode.SUCCESS.getCode());
                        svcDetailDTO.setMsgId(transId);
                        svcDetailDTO.setMsisdn(msisdn);
                        successSvcDetailDTOS.add(svcDetailDTO);
                    }
                }
                for (SuccessSvcDetailDTO successSvcDetailDTO : successSvcDetailDTOS) {
                    SmsMtRecord smsMtRecord = new SmsMtRecord();
                    try {
                        if (ErrorCode.SUCCESS.getCode().equals(successSvcDetailDTO.getStatus())) {
                            smsMtRecord.setMsgid(successSvcDetailDTO.getMsgId());
                            smsMtRecord.setMsisdn(successSvcDetailDTO.getMsisdn());
                            smsMtRecord.setSmsType(SMS_BLANK);
                            smsMtRecord.setPushStatus(SMS_PUSH_STATUS_WAIT);
                            Date date = new Date();
                            smsMtRecord.setSendTime(date);
                            long userId = LoginContextHolder.getContext().getUserId();
                            smsMtRecord.setCreateTime(date);
                            smsMtRecord.setCreateBy(userId);
                            smsMtRecord.setModifyTime(date);
                            smsMtRecord.setModifyBy(userId);
                            smsMtRecord.setDeleted(0);
                            this.baseMapper.insert(smsMtRecord);
                            log.info("[{}] success store down blankSms {}.", transId, smsMtRecord);
                        }
                    } catch (Exception e) {
                        log.error("[{}] store down blankSms {} error.", transId, smsMtRecord, e);
                    }
                }
            }
        }
    }

    /**
     * 调用发送下行空短信接口
     *
     * @param tokenValid token是否有效
     * @param transId    流水号
     * @param accountId  账户ID
     * @param blankSmsDTO    卡号
     * @return 返回 string
     * @throws Exception
     * @author zhanlele
     * @date 20200226 14:47:22
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    public ResultDTO doRequestSendBlankSms(boolean tokenValid, String transId, String accountId, BlankSmsDTO blankSmsDTO) throws Exception {
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }

        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        parameterMap.put(Constants.REQUEST_PARAM_MSISDNS, blankSmsDTO.getMsisdns());
        String validTime = blankSmsDTO.getValidTime();
        if (StringUtils.isNotEmpty(validTime)) {
            parameterMap.put(Constants.REQUEST_PARAM_VALIDTIME, validTime);
        }

        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, UrlConstants.OPERATE_DOWN_BLANK_SMS);
        log.info("[{}] sendDownBlankSms request url is {}.", transId, methodUrl);

        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));
        return tokenResultDTO;
    }
}
